var express = require('express');
var moment = require('moment')
var router = express.Router();
var articleModel = require('../db/articleModel')
// 首页路由
router.get('/',function(req,res){
    console.log(req.query);
    let page = parseInt(req.query.page||1);
    let size = parseInt(req.query.size||2);
    let username = req.session.username;
    console.log(username);
    
    articleModel.find().count().then(total=>{
        var totalPage = Math.ceil(total/size);
        articleModel.find().sort({creatTime:-1}).limit(size).skip((page-1)*size).then(docs=>{
            for(var i=0;i<docs.length;i++){
                docs[i].createTimeZH = moment(docs[i].createTime).format('YYYY-MM-DD HH:mm:ss');
            //    console.log(docs[i].createTimeZH );
               
            }
             res.render('index',{
                data:{
                    list:docs,
                    total:totalPage,
                    username
                  }                
                  
        })
    })
   
    })

    
})
// 注册页路由
router.get('/regist',function(req,res){
    res.render('regist',{})
})

// 登录页路由
router.get('/login',function(req,res){
    res.render('login',{})
})

// 写文章路由
router.get('/write',function(req,res){
    let id = req.query.id;
    let username = req.session.username;
    if(id){
        articleModel.findById(id).then(doc=>{
            // console.log({data:{
            //     username,
            //     doc
            // }});            
            res.render('write',{
                data:{
                    username,
                    doc
                }
            })
        })
    }else{
        // console.log({
        //     data:{
        //         username,
        //         doc:{
        //             _id:'',
        //             title:'',
        //             content:'',
        //             username
        //         }
        //     }
        // });       
        res.render('write',{
            data:{
                username,
                doc:{
                    _id:'',
                    title:'',
                    content:'',
                    username
                }
            }
        })
    }
    
})

// 详情页路由
router.get('/detail',function(req,res){
    let id = req.query.id;
    let username = req.session.username;
    // console.log(req.query);
    // console.log(req.session);
    articleModel.findById(id).then(doc=>{
        // console.log(doc);      
        doc.createTimeZH = moment(doc.createTime).format('YYYY-MM-DD HH:mm:ss')
       res.render('detail',{
           data:{
               username,
               doc
           }
       })  
    })
   
})
module.exports = router;
